package day16.pack5;

import java.io.*;

/**
 * 给一个目录路径，要求：打印该路径下所有子目录和文件。
 */
public class Test {
    public static void main(String[] args) throws IOException {
        File sourceFile = new File("D:\\", "apache-tomcat-9.0.39");
        File distFile = new File("E:\\", sourceFile.getName());
        xxx(sourceFile, distFile);
    }
    public static void xxx(File file, File distFile) throws IOException {
        if (file.isDirectory()) {
            // 创建目录E:/apache-tomcat-9.0
            distFile.mkdir();
            File[] files = file.listFiles(); // 获取所有子目录
            for (File childDirector: files) {
                xxx(childDirector, new File(distFile, childDirector.getName()));
            }
        } else {
            copy(file, distFile);
        }
    }



    public static void copy(File sourceFile, File distFile) throws IOException {
        if (!sourceFile.exists()) return;
        if (!distFile.exists()) distFile.createNewFile();
        // 简化finally中的判断关闭代码，但凡实现了Closeable接口的，可以写在try括号中，系统帮你关
        try (BufferedInputStream is = new BufferedInputStream(
                new FileInputStream(sourceFile), 1024 * 1024 * 20);
             BufferedOutputStream os = new BufferedOutputStream(
                     new FileOutputStream(distFile), 1024 * 1024 * 20)) {
            byte[] data = new byte[1024 * 512];
            int len = 0;
            while ((len = is.read(data)) != -1) {
                os.write(data, 0, len);
            }
            os.flush(); // 将剩余输出流的缓冲区内容冲刷到硬盘
        }
    }
}
